package com.whfp.coky.ui.base

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.whfp.coky.R
import com.whfp.coky.action.RecyclerViewAction
import com.whfp.coky.ui.base.vm.RecycleVM
import com.whfp.coky.utils.LogUtil
import com.whfp.coky.widget.RecycleViewDividerUtils

/**
 *T表示的是具体操作model
 * 刷新基类，预装载recyclerview所需要的的一些组件，待实现时初始化即可
 * created by coky on 2022/3/10
 */
abstract class BaseRecycleFrag<VM: RecycleVM<VB, T>,VB: ViewBinding,T>: BaseFragment<VM,VB>()
    ,RecyclerViewAction<T> {

    var mRecyclerView: RecyclerView? = null

    var mRefreshLayout: SmartRefreshLayout? = null

    override fun initView() {
        vModel.mAdapter = initAdapter(requireContext()).apply {
            itemClick {
                    it1 ->itemClick(it1)
            }
            itemLongClick {
                    it1 ->itemLongClick(it1)
            }
        }
        mRecyclerView = initRecycler()

        mRefreshLayout = initRefreshLayout().apply {
            setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
                override fun onRefresh(refreshLayout: RefreshLayout) {
                    vModel.onRefresh()
                }

                override fun onLoadMore(refreshLayout: RefreshLayout) {
                    vModel.onLoadMore(refreshLayout)
                }
            })
        }

        mRecyclerView?.let {
            it.adapter = vModel.mAdapter
            LogUtil.e("it.adapter is null??${it.adapter == null}")
            it.layoutManager = initLayoutManager()
            it.addItemDecoration(initDecoration())
        }
    }

    override fun initData() {
        vModel.buildRequest()
    }

//    fun httpNoMore() {
//        mRefreshLayout?.finishLoadMoreWithNoMoreData()
//    }



    fun httpFinshed() {
        mRefreshLayout?.let {
            it.finishRefresh()
            it.finishLoadMore()
        }
    }

    open fun initDecoration(): RecyclerView.ItemDecoration =
        RecycleViewDividerUtils(getAttachActivity()!!,
            LinearLayoutManager.HORIZONTAL, 2,
            resources.getColor( R.color.cj_gary))

    open fun initLayoutManager() = LinearLayoutManager(getAttachActivity())

    open fun itemClick(pos:Int){}
    open fun itemLongClick(pos:Int){}

}